<?php
/***********************************************************************
 * @package     IvanEngine
 * @subpackage  Core
 * @author      Ivan <ivanzx@msn.com>
 * @created     2010-07-17
 * @Purpose     CTagHelper defines some base helpers to construct html tags
 ***********************************************************************/
if(defined("IVANENGINE_CORE_TAGHELPER"))
    die("Redefinition macro in :".__FILE__."(".__LINE__.")");
define("IVANENGINE_CORE_TAGHELPER", true);

require_once (dirname(__FILE__).'/../Common.php');

/**
 * TagHelper defines some base helpers to construct html tags.
 *
 * @package    symfony
 * @subpackage helper
 * @author     Fabien Potencier <fabien.potencier@symfony-project.com>
 * @author     David Heinemeier Hansson
 * @version    SVN: $Id: TagHelper.php 13097 2008-11-18 06:58:24Z Kris.Wallsmith $
 */
class CTagHelper extends CBase
{
    public function __construct()
    {
        parent::__construct();
    }
    
    public function __destruct()
    {
        parent::__destruct();
    }
    
    /**
     * Constructs an html tag.
     *
     * @param  string $name     tag name
     * @param  array  $options  tag options
     * @param  bool   $open     true to leave tag open
     * @return string
     */
    static public function Tag($name, $options = array(), $open = false)
    {
        if (!$name)
        {
            return '';
        }

        return '<'.$name.self::_TagOptions($options).(($open) ? '>' : ' />');
    }

    static public function ContentTag($name, $content = '', $options = array())
    {
      if (!$name)
      {
        return '';
      }

      return '<'.$name.self::_TagOptions($options).'>'.$content.'</'.$name.'>';
    }

    static public function CdataSection($content)
    {
        return "<![CDATA[$content]]>";
    }

    /**
     * Wraps the content in conditional comments.
     *
     * @param  string $condition
     * @param  string $content
     *
     * @return string
     *
     * @see http://msdn.microsoft.com/en-us/library/ms537512(VS.85).aspx
     */
    static public function CommentAsConditional($condition, $content)
    {
        return "<!--[if $condition]>$content<![endif]-->";
    }

    /**
     * Escape carrier returns and single and double quotes for Javascript segments.
     */
    static public function EscapeJavascript($javascript)
    {
        $javascript = preg_replace('/\r\n|\n|\r/', "\\n", $javascript);
        $javascript = preg_replace('/(["\'])/', '\\\\\1', $javascript);

        return $javascript;
    }

    /**
     * Escapes an HTML string.
     *
     * @param  string $html HTML string to escape
     * @return string escaped string
     */
    static public function EscapeOnce($html)
    {
        return self::FixDoubleEscape(htmlspecialchars($html, ENT_COMPAT));
    }

    /**
     * Fixes double escaped strings.
     *
     * @param  string $escaped HTML string to fix
     * @return string fixed escaped string
     */
    static public function FixDoubleEscape($escaped)
    {
        return preg_replace('/&amp;([a-z]+|(#\d+)|(#x[\da-f]+));/i', '&$1;', $escaped);
    }

    static public function _TagOptions($options = array())
    {
        $options = self::_ParseAttributes($options);

        $html = '';
        foreach ($options as $key => $value)
        {
        $html .= ' '.$key.'="'.self::EscapeOnce($value).'"';
        }

        return $html;
    }

    static public function _ParseAttributes($string)
    {
        return is_array($string) ? $string : CStringHelper::ToArray($string);
    }

    static public function _GetOption(&$options, $name, $default = null)
    {
        if (array_key_exists($name, $options))
        {
            $value = $options[$name];
            unset($options[$name]);
        }
        else
        {
            $value = $default;
        }

        return $value;
    }

    /**
     * Returns a formatted ID based on the <i>$name</i> parameter and optionally the <i>$value</i> parameter.
     *
     * This static public function determines the proper form field ID name based on the parameters. If a form field has an
     * array value as a name we need to convert them to proper and unique IDs like so:
     * <samp>
     *  name[] => name (if value == null)
     *  name[] => name_value (if value != null)
     *  name[bob] => name_bob
     *  name[item][total] => name_item_total
     * </samp>
     *
     * <b>Examples:</b>
     * <code>
     *  echo GetIdFromName('status[]', '1');
     * </code>
     *
     * @param  string $name   field name
     * @param  string $value  field value
     *
     * @return string <select> tag populated with all the languages in the world.
     */
    static public function GetIdFromName($name, $value = null)
    {
        // check to see if we have an array variable for a field name
        if (strstr($name, '['))
        {
            $name = str_replace(array('[]', '][', '[', ']'), array((($value != null) ? '_'.$value : ''), '_', '_', ''), $name);
        }

        return $name;
    }

    /**
     * Converts specific <i>$options</i> to their correct HTML format
     *
     * @param  array $options
     * @return array returns properly formatted options
     */
    static public function _ConvertOptions($options)
    {
        $options = self::_ParseAttributes($options);

        foreach (array('disabled', 'readonly', 'multiple') as $attribute)
        {
            if (array_key_exists($attribute, $options))
            {
                if ($options[$attribute])
                {
                    $options[$attribute] = $attribute;
                }
                else
                {
                    unset($options[$attribute]);
                }
            }
        }

        return $options;
    }

}

class HTag extends CTagHelper{}
?>
